package blog.web.user;

import blog.sys.entity.User;
import blog.web.utils.MailUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import blog.sys.service.UserService;
import org.springframework.web.bind.annotation.RequestMapping;
import pub.spring.web.mvc.ActionResult;
import pub.types.Action;
import pub.web.ServletUtils;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.mail.MessagingException;
import javax.servlet.http.HttpServletRequest;
import java.beans.Encoder;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Date;

/**
 * Created by xyb on 2016-12-06.
 */
@Controller
public class MainController {


    /**
     * 用户登录
     *
     * @param acc  账号
     * @param pass 密码
     * @return
     * @throws UnsupportedEncodingException
     * @throws NoSuchAlgorithmException
     */
    @RequestMapping
    public ActionResult login(String acc, String pass) throws UnsupportedEncodingException, NoSuchAlgorithmException {
        User user = userService.getUserByAccount(acc);// 查询是否存在此账户
        boolean flag = false;
        ActionResult result = ActionResult.ok();
        if (user != null && !user.equals(null)) { // 存在此账户
            flag = checkPassWord(pass, user.getPassword());// 判断密码是否正确
        } else {
            result.setMsg("帐号不存在或者您还未激活帐户!");
            return result;
        }
        if (flag) {// 正确返回
            result.setData(user);
            result.setMsg("登录成功!");
            HttpServletRequest request = ServletUtils.getRequest();
            request.getSession().setAttribute("loginUser", user);
        } else {
            result.setMsg("账号密码错误!");
        }
        return result;
    }

    /**
     * 注册账户
     *
     * @param user
     * @return
     * @throws UnsupportedEncodingException
     * @throws NoSuchAlgorithmException
     */
    @RequestMapping
    public ActionResult register(User user) throws UnsupportedEncodingException, NoSuchAlgorithmException, MessagingException {
        ActionResult result = ActionResult.ok();
        boolean flag = ValidateMulUser(user.getMobile(), user.getEmail(), user.getNickName());
        if (flag) {
            user.setCreateTime(new Date());
            user.setUpdateTime(new Date());
            user.setType(1);
            user.setStatus(1);
            user.setPassword(EncoderByMd5(user.getPassword()));
            user.setActivation(0);
            Integer id = userService.userRegister(user);
            String email = userService.get(id).getEmail();
            String enCoderId = URLEncoder.encode(id.toString(), "utf-8");
            String emailMsg = "您好，请点击下面连接进行激活<a href='http://localhost:8080/jyan-app-server/user/on_activate_curr_user.json?userId=" + enCoderId + "'>http://localhost:8080/jyan-app-server/user/on_activate_curr_user.json?userId=" + enCoderId + "</a>";
            MailUtils.sendMail(email, emailMsg);
            result.setMsg("注册成功,之后请您尽快完成邮箱激活操作,否则您将不能登录!");
            result.setData(1);

        } else {
            result.setMsg("注册失败");
            result.setData(0);
        }
        return result;
    }

    /**
     * 根据用户id激活当前用户
     *
     * @param userId
     */
    @RequestMapping
    public ActionResult onActivateCurrUser(Integer userId) {
        if (userId != null) {
            userService.onActivateCurrUserService(userId);
        }
        ActionResult result = ActionResult.ok();
        result.setData("激活成功");
        result.setMsg("激活成功");
        return result;
    }

    /**
     * 判断是否之前已经有人注册过了
     *
     * @param mobile 手机
     * @param email  邮箱
     * @return
     */
    private boolean ValidateMulUser(String mobile, String email, String nickname) {
        boolean flag = userService.getUserByMobileOrEmail(mobile, email);
        if (!flag) {// 之前没有注册过
            boolean flag2 = userService.getUserByNickName(nickname);
            if (!flag2) {// 没人使用过的昵称
                return true;
            } else {// 已经有人使用
                return false;
            }
        } else {// 已经有人注册了
            return false;
        }
    }

    /**
     * 利用MD5进行加密
     *
     * @param str 待加密的字符串
     * @return 加密后的字符串
     * @throws NoSuchAlgorithmException     没有这种产生消息摘要的算法
     * @throws UnsupportedEncodingException
     */
    public static String EncoderByMd5(String str) throws NoSuchAlgorithmException, UnsupportedEncodingException {
        //确定计算方法
        MessageDigest md5 = MessageDigest.getInstance("MD5");
        BASE64Encoder base64en = new BASE64Encoder();
        //加密后的字符串
        String newStr = base64en.encode(md5.digest(str.getBytes("utf-8")));
        return newStr;
    }


    /**
     * 判断用户密码是否正确
     *
     * @param newpasswd 用户输入的密码
     * @param oldpasswd 数据库中存储的密码－－用户密码的摘要
     * @return
     * @throws NoSuchAlgorithmException
     * @throws UnsupportedEncodingException
     */
    private boolean checkPassWord(String newpasswd, String oldpasswd) throws NoSuchAlgorithmException, UnsupportedEncodingException {
        String encodePass = EncoderByMd5(newpasswd);
        if (encodePass.equals(oldpasswd) || newpasswd.equals(oldpasswd)) {
            return true;
        } else {
            return false;
        }
    }


    @Autowired
    private UserService userService;

}
